package cn.cjlmonster.hyouka_assistant.ai

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import cn.cjlmonster.hyouka_assistant.WKPlugin
import cn.cjlmonster.hyouka_assistant.base.BaseActivity
import cn.cjlmonster.hyouka_assistant.databinding.ActivityWebBrowserBinding
import cn.cjlmonster.hyouka_assistant.utils.UrlBuilder
import cn.cjlmonster.hyouka_assistant.webView.CustomWebChromeClient


/**
 * WebBrowser
 *
 * @author cjl
 * @date 2025/5/27 10:15
 */
class WebBrowser : BaseActivity<ActivityWebBrowserBinding>() {

    companion object {
        private const val TAG = WKPlugin.TAG

        @JvmStatic
        fun to(context: Context, url: String, query: Map<*, *>? = null) {
            context.startActivity(Intent(context, WebBrowser::class.java).apply {
                putExtra("url", UrlBuilder.buildUrlWithParams(url, query))
            })
        }
    }

    override fun createBinding() = ActivityWebBrowserBinding.inflate(layoutInflater)
    override fun bindWebView() = binding.webView

    override fun initViewModel() {
        immersiveNavigationBar()
        binding.webView.setWebViewClient(object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                binding.progressBar.visibility = View.VISIBLE
                binding.progressBar.progress = 0
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.progressBar.visibility = View.GONE
                binding.progressBar.progress = 0
            }
        })
        binding.webView.setWebChromeClient(object : CustomWebChromeClient(this) {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                binding.progressBar.progress = newProgress
            }
        })
        AIAssistantBridge(this, binding.webView) {
            finish()
        }
    }

    override fun initData() {
        val url = intent.getStringExtra("url")!!
        Log.i(TAG, "url: $url")
        binding.webView.loadUrl(url)
    }
}